/**
 * 菜单模块数据操作文件
 */

const { sequelize } = require('./common');
const { users, menu_list, role_menu } = sequelize.models;
let menus = null;

/**
 * 获取所有
 * @returns 
 */
const getAll = async () => menus || (menus = await menu_list.findAll({ order: ['sort'] }));

/**
 * 根据用户id获取菜单
 * @param {*} id 
 */
const getMenusByUserId = async id => {
    const user = await users.findOne({
        where: {
            id
        }
    });
    const { role_id } = user;
    const menus = await role_menu.findAll({ where: { role_id }, include: 'menu_list' });
    return menus.map(c => c.menu_list);
}

/**
 * 校验权限
 * @param {*} id 用户id
 * @param {*} codes 要校验的菜单编码
 */
const authorization = async (id, codes) => {
    const user = await users.findOne({
        where: {
            id
        }
    });
    const { role_id, status } = user;
    if (status == 0) {
        return null;
    }
    return await role_menu.findOne({
        attributes: ['role_id'],
        where: {
            role_id,
        },
        include: {
            model: menu_list,
            where: {
                code: codes
            }
        }
    });
}

/**
 * 根据角色ID获取所有的权限ID
 * @param {} role_id 
 * @returns 
 */
const getMenuIdsByRoleId = role_id => role_menu.findAll({
    attributes: ['menu_id'],
    where: {
        role_id
    }
})

module.exports = {
    getAll,
    authorization,
    getMenusByUserId,
    getMenuIdsByRoleId
}